import tornado.ioloop
import tornado.web
from tornado.options import define, options
import tornado.httpserver
import os.path

define("port", default=10001, help="run on the given port", type=int)


UPLOAD_FILE_PATH = 'D:/QtTestPro/HttpUpload/dw/'

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        args = dict(username = 'visitor')
        self.render('home.html', **args)

class UploadHandler(tornado.web.RequestHandler):

    # # 第一种写法
    def post(self):


        print("客户端上传文件进来");
        #username = self.get_argument('username', 'anonymous')

        if self.request.files.get('uploadfile', None):
            uploadFile = self.request.files['uploadfile'][0]
            filename = uploadFile['filename']
            fileObj = open(UPLOAD_FILE_PATH+filename, 'wb')
            fileObj.write(uploadFile['body'])

            self.write("上传成功")
        else:
            self.write("上传失败")

    # 第二种写法
    # def post(self):
    #     ret={'result':'OK'}
    #     upload_path = os.path.join(os.path.dirname(__file__), 'files')#文件的暂存路径
    #     file_metas = self.request.files.get('file', None)#提取表单中‘name’为‘file’的文件元数据
    #
    #     if not file_metas:
    #         ret['result'] = 'Invalid Args'
    #         return ret
    #
    #     for meta in file_metas:
    #         filename = meta['filename']
    #         file_path = os.path.join(upload_path, filename)
    #
    #         with open(file_path, 'wb') as up:
    #             up.write(meta['body'])
    #             # OR do other thing
    #
    #     self.write(json.dumps(ret))


application=tornado.web.Application([(r'/',MainHandler),('/upload', UploadHandler) ],
        template_path = 'templates',
        debug = True
        )

if __name__=='__main__':

    print("进来");
    application.listen(10001);
    print("开始监听");
    tornado.ioloop.IOLoop.instance().start()
    print("结束监听...");